package com.gxuwz.stats.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gxuwz.stats.entity.User;
import com.gxuwz.stats.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 个人信息 业务处理
 */
@RestController
@RequestMapping("/profile")
public class ProfileController {
    @Autowired
    private UserService userService;
//    @Autowired
//    private RedisTemplate<String, String> redisTemplate;

    /**
     * 获取当前登录用户的个人信息
     */
    @GetMapping("/information")
    public ResponseEntity<Map<String, Object>> getProfile() {
        // 获取当前认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 401);
            response.put("msg", "用户未登录");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
        }

        Object principal = authentication.getPrincipal();
        String username = null;
        if (principal instanceof org.springframework.security.core.userdetails.UserDetails) {
            username = ((org.springframework.security.core.userdetails.UserDetails) principal).getUsername();
        } else if (principal != null) {
            username = principal.toString();
        }

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (username != null) {
            queryWrapper.eq("username", username);
        }

        List<User> users = userService.list(queryWrapper);
        Map<String, Object> response = new HashMap<>();
        if (users != null && !users.isEmpty()) {
            response.put("code", 200);
            response.put("msg", "查询成功");
            response.put("user", users.get(0));
        } else {
            response.put("code", 404);
            response.put("msg", "找不到用户信息");
        }

        return ResponseEntity.ok(response);
    }

    /**
     * 用户页面-个人中心-修改用户密码
     * @param passwordInfo
     * @return
     */
    @PutMapping("/updateUserPwd")
    public ResponseEntity<Map<String, Object>> updatePwd(@RequestBody Map<String, String> passwordInfo) {
        String oldPassword = passwordInfo.get("oldPassword");
        String newPassword = passwordInfo.get("newPassword");
        // 从Spring Security上下文中获取当前认证用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Collections.singletonMap("message", "用户未登录"));
        }

        Object principal = authentication.getPrincipal();

        if (principal instanceof org.springframework.security.core.userdetails.User) {
            org.springframework.security.core.userdetails.User userDetails = (org.springframework.security.core.userdetails.User) principal;
            String username = userDetails.getUsername();

            // 验证旧密码是否正确 - 从数据库中查找具有该旧密码的用户记录

            User user = userService.findByPassword(username, oldPassword);
            Map<String, Object> response = new HashMap<>();
            if (user == null) {
                System.out.println("旧密码错误！");
                response.put("code", 400);
                response.put("message", "旧密码错误");
                return ResponseEntity.badRequest().body(response);
            }

            // 检查新旧密码是否相同
            if (oldPassword.equals(newPassword)) {
                response.put("code", 400);
                response.put("message", "新密码不能与旧密码相同");
                return ResponseEntity.badRequest().body(response);
//                return ResponseEntity.badRequest().body(Collections.singletonMap("message", "新密码不能与旧密码相同"));
            }

            // 更新密码
            if (userService.resetUserPwd(username, newPassword) > 0) {
                response.put("code", 200);
                response.put("message", "修改密码成功!");
                return ResponseEntity.ok(response);
//                return ResponseEntity.ok(Collections.singletonMap("message", "修改密码成功！"));
            } else {
                response.put("code", 500);
                response.put("message", "服务器内部错误");
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
//                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Collections.singletonMap("message", "服务器内部错误"));
            }
        } else {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 401);  // UNAUTHORIZED
            response.put("message", "用户未登录或会话已过期");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
//            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Collections.singletonMap("message", "用户未登录或会话已过期"));
        }
//
//        UserCo userCo = (UserCo) session.getAttribute("userCo");
//        if (userCo == null) {
//            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Collections.singletonMap("message", "用户未登录"));
//        }
//
//        // 验证旧密码是否正确 - 从数据库中查找具有该旧密码的用户记录
//        User user = userService.findByPassword(userCo.getUsername(), oldPassword);
//        System.out.println("user="+user);
//        if (user == null) {
//            return ResponseEntity.badRequest().body(Collections.singletonMap("message", "旧密码错误"));
//        }
//
//        // 检查新旧密码是否相同
//        if (oldPassword.equals(newPassword)) {
//            return ResponseEntity.badRequest().body(Collections.singletonMap("message", "新密码不能与旧密码相同"));
//        }
//
//        // 更新密码
//        if (userService.resetUserPwd(userCo.getUsername(), newPassword) > 0) {
//            return ResponseEntity.ok(Collections.singletonMap("message", "修改密码成功！"));
//        } else {
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Collections.singletonMap("message", "服务器内部错误"));
//        }
    }
}
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        System.out.println("Authentication: " + authentication); // 或者使用日志记录
//        if (authentication == null || !authentication.isAuthenticated()) {
//            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("User not authenticated");
//        }
//        String username = authentication.getName();
//        User user = userService.findByUsername(username);
//        if (user == null) {
//            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User not found");
//        }
//        return ResponseEntity.ok(); // 返回用户对象或其他相关信息

//    @GetMapping("/information")
//    public ResponseEntity<?> getProfile() {
////        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
////        System.out.println("Authentication: " + authentication); // 或者使用日志记录
////        if (authentication == null || !authentication.isAuthenticated()) {
////            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("User not authenticated");
////        }
////        String username = authentication.getName();
////        User user = userService.findByUsername(username);
////        if (user == null) {
////            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User not found");
////        }
//        return ResponseEntity.ok(); // 返回用户对象或其他相关信息
//    }
//}

//    @GetMapping("/information")
//    @Cacheable(value = "userProfiles", key = "#userCo.id", unless = "#result == null")
//    public ResponseEntity<?> getProfile(HttpSession session, @AuthenticationPrincipal UserDetails userDetails) {
//        // 如果用户没有认证，则返回401状态码
//        if (userDetails == null) {
//            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
//        }
//
//        // 从认证信息中获取用户ID或其他标识符
//        String userId = userDetails.getUsername(); // 假设用户名即为用户ID
//
//        // 直接从数据库获取用户信息（如果不在缓存中）
//        User user = userService.getById(userId);
//
//        // 返回用户信息或404未找到
//        return user != null ? ResponseEntity.ok(user) : ResponseEntity.notFound().build();
//    }
//}